package com.cjxy.parking.config;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.cjxy.parking.common.R;
import com.cjxy.parking.entity.po.User;
import com.cjxy.parking.service.UserService;
import com.cjxy.parking.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户上下文拦截器
 * 用于在请求处理前将用户信息存入上下文
 *
 * @author: YourName
 * @date: 2025-10-26
 */
@Component
@RequiredArgsConstructor
public class UserContextInterceptor implements HandlerInterceptor {
    
    private final UserService userService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 检查用户是否登录
        if (StpUtil.isLogin()) {
            try {
                // 获取当前登录用户的ID
                SaSession session = StpUtil.getSession();
                // 取出登录时存入的用户信息
                User user = session.getModel("userInfo", User.class);
                
                if (user != null) {
                    // 将用户信息存入上下文
                    UserContext.setUser(user);
                }
                return true;
            } catch (Exception e) {
                // 处理会话异常
                UserContext.clear();
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(JSON.toJSONString(R.error("会话异常，请重新登录")));
                return false;
            }
        } else {
            // 未登录，清空用户信息
            UserContext.clear();
            // 返回未登录的响应
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(JSON.toJSONString(R.error("未登录")));
            return false;
        }
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求处理完成后清除上下文信息
        UserContext.clear();
    }
}